package servlet;

import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.ActorService;
import service.UserService;
import util.DateUtil;
import util.RegexUtil;
import util.Title;
import util.TitleUtil;

import domain.Actor;
import domain.User;
import ex.DatabaseException;
import ex.RegistrationFailedException;


public class EditProfile extends HttpServlet {
	
	UserService userService=new UserService();
	ActorService actorService=new ActorService();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session=request.getSession();
		if(session.getAttribute("user")!=null){
			User user=(User) session.getAttribute("user");
			if(user!=null)
			{
				String action=request.getParameter("action");
				if(!RegexUtil.isNullOrEmpty(action)){
					if(action.equalsIgnoreCase("save")){
						request.getAttribute("firstname");
					}
					else{
						response.sendRedirect("home");
					}
				}
				else{
					
					Map<Title,Boolean> hasTitles=TitleUtil.getTitlesByUser(user);
					
					request.setAttribute("hasTitles", hasTitles);
					
					RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/user-edit.jsp");
					if (dispatcher != null) dispatcher.forward(request, response);
				}
			}
			else{
				response.sendRedirect("home");
			}
		}
		else{
			response.sendRedirect("home");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User tmpUser=null;
		HttpSession session=request.getSession();
		try{			
			if(session.getAttribute("user")!=null){
				User user=(User) session.getAttribute("user");
				if(user!=null)
				{
					tmpUser=user;
					Map<Title,Boolean> hasTitles=TitleUtil.getTitlesByUser(user);
					
					request.setAttribute("hasTitles", hasTitles);
					
					String firstName=request.getParameter("firstname");
					String surname=request.getParameter("surname");
					//String image=request.getParameter("image");
					String imageURL=request.getParameter("imageURL");			
					Date birthDate=getDate(request, response);
					String city=request.getParameter("city");
					String tel=request.getParameter("tel");
					String description=request.getParameter("description");
					boolean availabilibty=request.getParameterValues("availability")!=null && request.getParameterValues("availability").length>0;
					
					//storing what titles the user has marked through bitwise operation
					int titleBits = getTitleBits(request, response);
					if(titleBits!=-1){
						
						boolean actorSelected=(titleBits & TitleUtil.actor_bit)==TitleUtil.actor_bit;
						
						if(actorSelected){
							String heightString=request.getParameter("height");
							int height=0;
							if(!RegexUtil.isParsableToInt(heightString)){
								throw new RegistrationFailedException("Height is not in correct format!");
							}
							else{
								height=Integer.parseInt(heightString);
							}
							String weightString=request.getParameter("weight");
							int weight=0;
							if(!RegexUtil.isParsableToInt(weightString)){
								throw new RegistrationFailedException("Weight is not in correct format!");
							}
							else{
								weight=Integer.parseInt(weightString);
							}
							String hairColor=request.getParameter("hair");
							String skinColor=request.getParameter("skin");
							String eyeColor=request.getParameter("eyes");
							Actor actor=user.getActorFeatures();
							if(actor!=null){
								actor.setHeight(height);
								actor.setWeight(weight);
								actor.setHairColor(hairColor);
								actor.setSkinColor(skinColor);
								actor.setEyeColor(eyeColor);
								
								user.setActorFeatures(actor);
							}
							else
							{
								actor=new Actor(-1, hairColor, eyeColor,skinColor, height, weight);
								user.setActorFeatures(actor);
							}							
						}
						else
						{
							Actor actor=user.getActorFeatures();
							if(actor!=null){
								actorService.deleteActor(actor);
								user.setActorFeatures(null);
							}							
						}
					}
					user.setFirstName(firstName);
					user.setLastName(surname);
					user.setDateOfBirth(birthDate);
					user.setImageURL(imageURL);
					user.setSummary(description);
					user.setCity(city);
					user.setTel(tel);
					user.setTitle(titleBits);
					user.setAvailable(availabilibty);
					userService.updateUser(user);
					user= userService.authenticateUser(user.getEmail(), user.getPassword());
					session.setAttribute("user", user);
					response.sendRedirect("user?who=me");
				}
			}
		}
		catch (RegistrationFailedException e) {
			request.setAttribute("updateError", e.getMessage());
			
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/user-edit.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
		catch (DatabaseException e) {
			request.setAttribute("updateError", e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/user-edit.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
		catch (ParseException e) {
			request.setAttribute("updateError", e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/user-edit.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
		catch (Exception e) {
			request.setAttribute("updateError", "A general error occured:" + e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/user-edit.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
	}
	
	protected Date getDate(HttpServletRequest request, HttpServletResponse response) throws ParseException{
		String day= request.getParameter("day");
		String month=request.getParameter("month");
		String year=request.getParameter("year");
		
		String datetimeString=year+" " + month + " " + day;
		return DateUtil.convertStringToDateYYYYMMDD(datetimeString);
	}
	
	protected int getTitleBits(HttpServletRequest request, HttpServletResponse response) throws ParseException{
		String[] titles = request.getParameterValues("title");

		//storing what titles the user has marked through bitwise operation
		int titleBits = 0x00;
		if (titles != null) {
			Title title;
			for (int i = 0; i < titles.length; i++)	{
				String value=titles[i];
				if(!RegexUtil.isNullOrEmpty(value)){
					title=TitleUtil.getTitleByTitleName(value);
					if(title!=null){
						titleBits |= title.getTitleBit();
					}
				}
			}
			return titleBits;
		}
		return -1;
	}

}
